import Cache from '@/utils/cache'
import { USER_INFO, TOKEN } from '../../config/cachekey';
const state = {
	userInfo: {
		nickname: '微信用户',
		avatar: "",
		gender: 0, //用户性别，0: 未知；1:男性；2:女性
		region: '未设置',
		historyNum: 0, //识别历史数,
		favoriteNum: 0, //收藏历史数
	},
	token: Cache.get(TOKEN) || null,
}

const mutations = {
	LOGIN(state, opt) {
		state.token = opt._id;
		Cache.set(TOKEN, opt._id, 59 * 24 * 60 * 60);
		this.dispatch('getUser')
	},
	LOGOUT(state) {
		state.token = undefined;
		state.userInfo = {
			nickname: '微信用户',
			avatar: "",
			gender: 0, //用户性别，0: 未知；1:男性；2:女性
			region: '未设置',
			historyNum: 0, //识别历史数,
			favoriteNum: 0, //收藏历史数
		}
		Cache.remove(TOKEN)
	},
	SETUSERINFO(state, user) {
		state.userInfo = user
	},

}

const actions = {

	getUser({
		state,
		commit
	}) {
		return new Promise(resolve => {
			wx.cloud.callFunction({name: 'user', data: {$url: "get", queryData: {_id: state.token}}}).then(response => {
				if (response.result.code == 200) {
					commit('SETUSERINFO', response.result.data)
				}
				resolve()
			})
		})
	}
}

export default {
	state,
	mutations,
	actions
};